/*
 * @lc app=leetcode.cn id=794 lang=typescript
 *
 * [794] 有效的井字游戏
 */

// @lc code=start
function validTicTacToe(board: string[]): boolean {
  const n = board.length;
  let xCount = 0;
  let oCount = 0;
  const isWin = (char: string): boolean => {
    // 横竖连续3个相等，表示字符是char的一方获胜
    for (let i = 0; i < n; i++) {
      if (board[0][i] === char && board[1][i] === char && board[2][i] === char) return true;

      if (board[i][0] === char && board[i][1] === char && board[i][2] === char) return true;
    }
    // 斜线连续3个相等，表示字符是char的一方获胜
    if (board[0][0] === char && board[1][1] === char && board[2][2] === char) return true;
    if (board[0][2] === char && board[1][1] === char && board[2][0] === char) return true;
    return false;
  };
  // 计算棋盘x和o的个数
  // x先手，所以x>=o
  for (let row of board) {
    for (let char of row) {
      if (char === 'X') {
        xCount++;
      } else if (char === 'O') {
        oCount++;
      }
    }
  }
  // 判断x和o的个数是否合法
  if (xCount !== oCount && xCount !== oCount + 1) return false;
  // 如果x获胜，那么棋盘上x比o多一个
  if (isWin('X') && xCount !== oCount + 1) return false;
  // 如果o获胜，那么棋盘上x和o数量相等
  if (isWin('O') && xCount !== oCount) return false;

  return true;
}
// @lc code=end
